package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {


    @Autowired
    private CheckGroupMapper checkGroupMapper;

    //查询
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //完成分页查询，基于mabatis的分页助手插件完成
        PageHelper.startPage(currentPage, pageSize);

        Page<CheckItem> page = checkGroupMapper.selectByCondition(queryString);
        long total = page.getTotal();
        List<CheckItem> rows = page.getResult();
        return new PageResult(total, rows);
    }

    //新增检查组，同时让检查组关联检查项
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {

        //新增检查组，关联检查组t_checkgroup表
        checkGroupMapper.add(checkGroup);

        //设置检查组与检查项的多对多关联关系，操作t_checkgroup_checkitem表
        Integer checkGroupId = checkGroup.getId();
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                checkGroupMapper.insert(checkGroupId, checkitemId);
            }

        }

    }

    //根据id查询检查组
    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupMapper.findById(id);
    }

    @Override
    public List<Integer> findCheckitemIdsByCheckgroupId(Integer id) {
        return checkGroupMapper.findCheckitemIdsByCheckgroupId(id);
    }

    //编辑检查组信息同时关联检查项
    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //  修改检查组基本信息，操作检查组t_checkgroup表
        checkGroupMapper.edit(checkGroup);
        //清理当前检查组关联的检查项，操作中间关联表t_checkgroup_checkitem表
        checkGroupMapper.deleteAssocication(checkGroup.getId());
        //重新建立检查组和检查项的关联关系
        Integer checkGroupId = checkGroup.getId();
        if (checkitemIds != null && checkitemIds.length > 0) {
            for (Integer checkitemId : checkitemIds) {
                checkGroupMapper.insert(checkGroupId, checkitemId);
            }

        }
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();
    }
}
